<template>
    <custom-page-box>
        <div class="need-manage-container">
            <div class="search-box">
                <a-form-model layout="inline" :model="form" ref="ruleForm">
                    <a-form-model-item prop="title" class="title-input">
                        <a-input v-model="form.title" placeholder="标题" :allowClear="true"></a-input>
                    </a-form-model-item>
                    <a-form-model-item prop="type" class="form-type">
                        <a-cascader
                            v-model="form.type"
                            :options="reallTreeData"
                            placeholder="分类"
                            change-on-select
                            :allowClear="true"
                            :field-names="{ label: 'name', value: 'id', children: 'children' }"
                        />
                    </a-form-model-item>
                    <a-form-model-item prop="releaseState" class="form-type">
                        <a-select v-model="form.releaseState" placeholder="发布状态" :allowClear="true">
                            <a-select-option :value="1">已发布</a-select-option>
                            <a-select-option :value="0">未发布</a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item prop="effectiveState" class="form-type">
                        <a-select v-model="form.effectiveState" placeholder="生效状态" :allowClear="true">
                            <a-select-option :value="1">生效中</a-select-option>
                            <a-select-option :value="2">需求完成</a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item prop="orgCategoryId" class="form-type">
                        <a-select v-model="form.orgCategoryId" placeholder="来源" :allowClear="true">
                            <a-select-option value="3">运营端</a-select-option>
                            <a-select-option value="4">服务商</a-select-option>
                            <a-select-option value="5">投资商</a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item prop="time" class="time-arr">
                        <a-range-picker
                            :placeholder="['发起开始时间', '结束时间']"
                            @change="onChange"
                            :key="key"
                            :allowClear="true"
                        />
                    </a-form-model-item>
                    <a-form-model-item prop="cityCode" class="city-input">
                        <city-cascader v-model="form.cityCode"></city-cascader>
                    </a-form-model-item>
                    <a-form-model-item>
                        <a-button class="search-btn add" @click="searchTable('toOne')">搜索</a-button>
                    </a-form-model-item>
                    <a-form-model-item>
                        <a-button class="add" @click="addNeed">发布需求</a-button>
                    </a-form-model-item>
                </a-form-model>
            </div>
            <div class="table">
                <a-table
                    :data-source="tableData"
                    rowKey="id"
                    :pagination="false"
                    :row-selection="{
                        selectedRows: selectedRows,
                        selectedRowKeys: selectedRowKeys,
                        onChange: onSelectChange
                    }"
                    :scroll="{ x: width, y: height }"
                >
                    <a-table-column key="x" title="序号" width="60px" align="center">
                        <template slot-scope="text, record, index">
                            <span>{{ (pageIndex - 1) * pageSize + index + 1 }}</span>
                        </template>
                    </a-table-column>
                    <a-table-column key="title" title="标题" data-index="title" width="80px">
                        <template slot-scope="text, record">
                            <div @click="toEdit(record, 'detail')" :title="record.title" class="textEllipsis">
                                {{ record.title }}
                            </div>
                        </template>
                    </a-table-column>
                    <a-table-column key="enterDemandType" title="类型" data-index="enterDemandType" width="120px">
                        <template slot-scope="text, record">
                            <span v-if="record.enterDemandType === 1">房源</span>
                            <span v-if="record.enterDemandType === 2">地块</span>
                            <span v-if="record.enterDemandType === 3">人才</span>
                            <span v-if="record.enterDemandType === 4">农产品</span>
                            <span v-if="record.enterDemandType === 5" :title="record.enterDemandName">{{
                                record.enterDemandName
                            }}</span>
                        </template>
                    </a-table-column>
                    <a-table-column key="areaName" title="省市区镇" data-index="areaName" width="160px" />
                    <a-table-column key="publishStatus" title="发布状态" data-index="publishStatus" width="80px">
                        <template slot-scope="text, record">
                            <span :class="record.publishStatus === 2 ? 'red-txt' : 'green-txt'">{{
                                record.publishStatus === 2 ? '未发布' : '已发布'
                            }}</span>
                        </template>
                    </a-table-column>
                    <a-table-column key="takeEffectStatus" title="生效状态" data-index="takeEffectStatus" width="80px">
                        <template slot-scope="text, record">
                            <span :class="record.takeEffectStatus === 1 ? 'blue-txt' : 'green-txt'">{{
                                record.takeEffectStatus === 1 ? '生效中' : '需求完成'
                            }}</span>
                        </template>
                    </a-table-column>
                    <a-table-column key="personnelName" title="联系人姓名" data-index="personnelName" width="100px" />
                    <a-table-column key="phone" title="联系人手机号" data-index="phone" width="110px" />
                    <a-table-column key="orgCategoryId" title="来源" data-index="orgCategoryId" width="110px">
                        <template slot-scope="text, record">
                            {{
                                record.orgCategoryId === '3'
                                    ? '运营端'
                                    : record.orgCategoryId === '4'
                                        ? '服务端'
                                        : record.orgCategoryId === '5'
                                            ? '投资商'
                                            : ''
                            }}
                        </template>
                    </a-table-column>
                    <a-table-column key="createTime" title="添加时间" data-index="createTime" width="150px" />
                    <a-table-column key="userName" title="添加人" data-index="userName" width="80px" />
                    <a-table-column key="c" title="操作" width="190px">
                        <template slot-scope="text, record">
                            <!-- <a-button class="green" @click="toRelease(text)" v-if="record.publishStatus === 2">
                                发布
                            </a-button> -->
                            <a-button
                                class="blue"
                                @click="toRecall(text)"
                                v-if="record.publishStatus !== 2 && record.orgCategoryId === '3'"
                            >
                                撤回
                            </a-button>
                            <a-button
                                class="green"
                                @click="toFinish(text)"
                                v-if="record.publishStatus !== 2 && record.takeEffectStatus === 1 && record.orgCategoryId === '3'"
                            >
                                完成
                            </a-button>
                            <a-button
                                class="green"
                                @click="toEdit(text)"
                                v-if="record.publishStatus === 2 && record.orgCategoryId === '3'"
                            >
                                编辑
                            </a-button>
                            <a-button
                                class="red"
                                @click="toDelete(text)"
                                v-if="
                                    (record.orgCategoryId === '3' && record.publishStatus === 2) ||
                                        record.orgCategoryId !== '3'
                                "
                            >
                                删除
                            </a-button>
                        </template>
                    </a-table-column>
                </a-table>
            </div>
        </div>

        <custom-pagination
            :total="Number(total)"
            :page.sync="pageIndex"
            :limit.sync="pageSize"
            @pagination="searchTable"
        >
            <div class="pagination-tool">
                <p>
                    已选<span class="num">{{ selectedRows.length }}</span>条
                </p>
                <!-- <a-button :disabled="canRelease" @click="toRelease()">批量发布</a-button> -->
                <a-button :disabled="canRecall" @click="toRecall()">批量撤回</a-button>
                <a-button :disabled="canFinish" @click="toFinish()">批量完成</a-button>
                <a-button :disabled="canDelete" @click="toDelete()">批量删除</a-button>
            </div>
        </custom-pagination>
        <a-modal
            :visible="addShow"
            :footer="null"
            dialogClass="add-need-dialog"
            width="800px"
            @cancel="addShow = false"
        >
            <div class="add-need-dialog-body">
                <div class="three">
                    <p class="title">企业需求</p>
                    <div class="content">
                        <div class="item" @click="toAdd('houses')">
                            <p>找房源</p>
                        </div>
                        <div class="item" @click="toAdd('plot')">
                            <p>找土地</p>
                        </div>
                        <div class="item" @click="toAdd('talents')">
                            <p>找人才</p>
                        </div>
                        <div class="item" @click="toAdd('product')">
                            <p>找产品</p>
                        </div>
                        <div class="item" @click="toAdd('service')">
                            <p>找服务</p>
                        </div>
                    </div>
                </div>
            </div>
        </a-modal>
        <a-modal
            title="确认要删除这条需求吗？"
            :visible="show"
            :confirm-loading="confirmLoading"
            @ok="handleOk"
            @cancel="handleCancel"
        >
            <a-form-model ref="deleteForm" :model="deleteForm" :rules="rules">
                <a-form-model-item prop="deleteMark">
                    <a-textarea
                        v-model="deleteForm.deleteMark"
                        placeholder="删除原因（必填）"
                        :rows="4"
                        :maxLength="100"
                    />
                </a-form-model-item>
            </a-form-model>
        </a-modal>
    </custom-page-box>
</template>

<script>
import CityCascader from '@/components/city-cascader'
import { localStorage } from '~/plugins/tools'

export default {
    name: 'NeedManageServiceList',
    components: {
        CityCascader
    },
    beforeRouteEnter (to, from, next) {
        if (['/need-manage/talents', '/need-manage/houses', '/need-manage/plot', '/need-manage/product', '/need-manage/service'].includes(from.path)) {
            next((vm) => {
                vm.searchTable()
            })
        } else {
            next()
        }
    },
    data () {
        return {
            deleteForm: {
                deleteMark: ''
            },
            rules: {
                deleteMark: [{ required: true, message: '请输入删除原因', trigger: 'blur' }]
            },
            activeName: '3',
            form: {
                title: '',
                type: [],
                // 发布状态
                releaseState: undefined,
                // 生效状态
                effectiveState: undefined,
                time: [],
                cityCode: '',
                orgCategoryId: undefined
            },
            key: 0,
            treeData: [],
            reallTreeData: [],
            typeListDis: [],
            total: 0,
            pageIndex: 1,
            pageSize: 10,
            tableData: [],
            selectedRows: [],
            selectedRowKeys: [],
            width: 1000,
            height: 500,
            addShow: false,
            show: false,
            confirmLoading: false,
            deleteRow: {},
            isOpera: true
        }
    },
    computed: {
        canRelease () {
            if (!this.selectedRows.length) return true
            let arr = []
            if (this.activeName !== '1') {
                arr = this.selectedRows.filter(item => ![2].includes(item.publishStatus))
            } else {
                arr = this.selectedRows.filter(item => ![0].includes(item.releaseState))
            }
            return !!arr.length
        },
        canRecall () {
            if (!this.selectedRows.length) return true
            let arr = []
            if (this.activeName !== '1') {
                arr = this.selectedRows.filter(item => ![1].includes(item.publishStatus))
            } else {
                arr = this.selectedRows.filter(item => ![1].includes(item.releaseState))
            }
            return !!arr.length
        },
        canFinish () {
            if (!this.selectedRows.length) return true
            let arr = []
            if (this.activeName !== '1') {
                arr = this.selectedRows.filter(item => ![1].includes(item.takeEffectStatus))
            } else {
                arr = this.selectedRows.filter(item => ![1].includes(item.effectiveState))
            }
            return !!arr.length
        },
        canDelete () {
            if (!this.selectedRows.length) return true
            let arr = []
            if (this.activeName !== '1') {
                arr = this.selectedRows.filter(item => ![2].includes(item.publishStatus))
            } else {
                arr = this.selectedRows.filter(item => ![0].includes(item.releaseState))
            }
            return !!arr.length
        }
    },
    created () {},
    async mounted () {
        await this.getTypeList()
        this.searchTable()
        this.getTree()
        const arr = document.getElementsByClassName('table')
        if (arr[0]) {
            this.width = arr[0].offsetWidth - 17
            this.height = arr[0].offsetHeight - 59 + 17
        }
        this.isOpera = ['1', '2', '3'].includes(localStorage.getItem('userInfo').orgCategoryId)
    },
    methods: {
        async getTypeList () {
            const res = await this.$ApiServer['need/getTypeList']()
            if (res.code === 200) {
                this.typeListDis = res.data
            }
        },
        searchTable (type) {
            if (type === 'toOne') this.pageIndex = 1
            this.getTableBusinessNeed()
        },
        async getTree () {
            const res = await this.$ApiServer['operationConfig/getTree']()
            if (res.code === 200) {
                const add = (list) => {
                    list.forEach((item) => {
                        item.scopedSlots = { title: 'custom' }
                        if (item.children && item.children.length) {
                            item.children = add(item.children)
                        } else {
                            item.children = []
                        }
                    })
                    return list
                }
                this.treeData = add(res.data)
                const filterStatus = (list) => {
                    return list.filter((item) => {
                        if (item.children) {
                            item.children = filterStatus(item.children)
                        }
                        return item.status
                    })
                }
                this.treeData = filterStatus(this.treeData)
                this.treeData.forEach((item) => {
                    if (item.children) {
                        item.children.forEach((it) => {
                            delete it.children
                        })
                    }
                })
                this.reallTreeData = [
                    {
                        id: 1,
                        name: '房源'
                    },
                    {
                        id: 2,
                        name: '地块'
                    },
                    {
                        id: 3,
                        name: '人才'
                    },
                    {
                        id: 4,
                        name: '农产品'
                    },
                    {
                        id: 5,
                        name: '服务',
                        children: this.treeData
                    }
                ]
            }
        },
        onChange (date, dateString) {
            this.form.time = dateString
        },
        // 企业需求列表
        async getTableBusinessNeed () {
            const { title, type, releaseState, effectiveState, time, cityCode, orgCategoryId } = this.form
            console.log(type)
            const res = await this.$ApiServer['need/list/businessNeed']({
                currentPage: this.pageIndex,
                pageSize: this.pageSize,
                title,
                type:
                    type.length && type[0] === 5
                        ? type.length === 1 || type.length === 2
                            ? ''
                            : type[type.length - 1]
                        : '',
                firstKind: type.length && type[0] === 5 && type.length === 2 ? type[1] : undefined,
                enterDemandType: type.length ? type[0] : '',
                publishStatus: releaseState === 1 ? 1 : releaseState === 0 ? 2 : '',
                takeEffectStatus: effectiveState,
                createTime: time[0],
                endTime: time[1],
                areaCode: cityCode,
                orgCategoryId
            })
            if (res.code === 200) {
                this.tableData = res.data.records || []
                this.total = res.data.total
            } else {
                this.tableData = []
                this.total = 0
                this.$message.error(res.message)
            }
        },
        onSelectChange (selectedRowKeys, selectedRows) {
            this.selectedRowKeys = selectedRowKeys
            this.selectedRows = selectedRows
        },
        toRelease (row) {
            this.$confirm({
                title: '提示',
                content: row ? '确认是否发布需求[' + (row.title || row.name) + ']' : '确认是否发布选中需求',
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                    let url = ''
                    switch (this.activeName) {
                    case '1':
                        url = 'need/release'
                        break
                    case '2':
                        url = 'need/townService/release'
                        break
                    case '3':
                        url = 'need/company/release'
                        break
                    }
                    const res = await this.$ApiServer[url](this.getIds(row))
                    if (res.code === 200) {
                        this.selectedRows = []
                        this.selectedRowKeys = []
                        this.searchTable()
                        this.$message.success(res.message)
                    } else {
                        this.$message.error(res.message)
                    }
                },
                onCancel () {}
            })
        },
        toRecall (row) {
            this.$confirm({
                title: '提示',
                content: row ? '确认是否撤回需求[' + (row.title || row.name) + ']' : '确认是否撤回选中需求',
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                    let url = ''
                    switch (this.activeName) {
                    case '1':
                        url = 'need/recall'
                        break
                    case '2':
                        url = 'need/townService/recall'
                        break
                    case '3':
                        url = 'need/company/recall'
                        break
                    }
                    const res = await this.$ApiServer[url](this.getIds(row))
                    if (res.code === 200) {
                        this.selectedRows = []
                        this.selectedRowKeys = []
                        this.searchTable()
                        this.$message.success(res.message)
                    } else {
                        this.$message.error(res.message)
                    }
                },
                onCancel () {}
            })
        },
        toFinish (row) {
            this.$confirm({
                title: '提示',
                content: row ? '确认是否完成需求[' + (row.title || row.name) + ']' : '确认是否完成选中需求',
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                    let url = ''
                    switch (this.activeName) {
                    case '1':
                        url = 'need/finish'
                        break
                    case '2':
                        url = 'need/townService/finish'
                        break
                    case '3':
                        url = 'need/company/finish'
                        break
                    }
                    const res = await this.$ApiServer[url](this.getIds(row))
                    if (res.code === 200) {
                        this.selectedRows = []
                        this.selectedRowKeys = []
                        this.searchTable()
                        this.$message.success(res.message)
                    } else {
                        this.$message.error(res.message)
                    }
                },
                onCancel () {}
            })
        },
        toEdit (row, type) {
            if (row.dataType === 1 || row.dataType === 2) {
                this.$router.push({
                    path: '/need-manage/investment-promotion',
                    query: {
                        formType: row.dataType === 1 ? 'attractCapital' : 'merchants',
                        id: row.id,
                        d: type === 'detail' ? 'd' : ''
                    }
                })
            } else if (row.enterDemandType) {
                let name = ''
                switch (row.enterDemandType) {
                case 1:
                    name = 'houses'
                    break
                case 2:
                    name = 'plot'
                    break
                case 3:
                    name = 'talents'
                    break
                case 4:
                    name = 'product'
                    break
                case 5:
                    name = 'service'
                    break
                }
                this.$router.push({
                    path: `/need-manage/${name}`,
                    query: {
                        id: row.id,
                        d: type === 'detail' ? 'd' : ''
                    }
                })
            } else {
                this.$router.push({
                    path: '/need-manage/townService',
                    query: {
                        id: row.id,
                        d: type === 'detail' ? 'd' : ''
                    }
                })
            }
        },
        toDelete (row) {
            const arr = this.selectedRows.filter(item => item.sourceType === 2 || item.sourceType !== 1)
            if (this.activeName === '3' && (row ? row.sourceType === 2 || row.sourceType !== 1 : arr.length)) {
                this.show = true
                this.deleteRow = row
                return false
            }
            this.$confirm({
                title: '提示',
                content: row ? '确认是否删除需求[' + (row.title || row.name) + ']' : '确认是否删除选中需求',
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                    let url = ''
                    switch (this.activeName) {
                    case '1':
                        url = 'need/delete'
                        break
                    case '2':
                        url = 'need/townService/delete'
                        break
                    case '3':
                        url = 'need/company/delete'
                        break
                    }
                    const res = await this.$ApiServer[url](this.getIds(row))
                    if (res.code === 200) {
                        this.selectedRows = []
                        this.selectedRowKeys = []
                        this.searchTable()
                        this.$message.success(res.message)
                    } else {
                        this.$message.error(res.message)
                    }
                },
                onCancel () {}
            })
        },
        handleOk () {
            this.confirmLoading = true
            this.$refs.deleteForm.validate(async (valid) => {
                if (valid) {
                    const res = await this.$ApiServer['need/company/delete'](this.getIds(this.deleteRow))
                    if (res.code === 200) {
                        this.$message.success(res.message)
                        this.selectedRows = []
                        this.selectedRowKeys = []
                        this.searchTable()
                        this.show = false
                        this.confirmLoading = false
                        this.deleteForm.deleteMark = ''
                    } else {
                        this.$message.error(res.message)
                        this.confirmLoading = false
                    }
                } else {
                    this.confirmLoading = false
                }
            })
        },
        handleCancel () {
            this.$refs.deleteForm.resetFields()
            this.deleteForm.deleteMark = ''
            this.show = false
        },
        addNeed () {
            this.addShow = true
        },
        toAdd (type) {
            this.addShow = false
            if (type === 'attractCapital' || type === 'merchants') {
                this.$router.push({
                    path: '/need-manage/investment-promotion',
                    query: {
                        formType: type
                    }
                })
            } else {
                this.$router.push({
                    path: `/need-manage/${type}`
                })
            }
        },
        getIds (row) {
            const obj = {}
            if (this.activeName === '1') {
                obj.ids = row ? [row.id] : this.selectedRows.map(item => item.id)
            } else if (this.activeName === '2') {
                obj.ids = row ? [row.id] : this.selectedRows.map(item => item.id)
            } else {
                obj.batchOperateList = row
                    ? [
                        {
                            id: row.id,
                            enterDemandType: row.enterDemandType,
                            message: this.deleteForm.deleteMark
                        }
                    ]
                    : this.selectedRows.map((item) => {
                        return {
                            id: item.id,
                            enterDemandType: item.enterDemandType,
                            message: this.deleteForm.deleteMark
                        }
                    })
            }
            return obj
        }
    }
}
</script>

<style scoped lang="less">
.head-tips {
    background-color: rgba(6, 123, 255, 0.1);
    border-left: 6px solid rgba(6, 123, 255, 1);
    height: 68px;
    padding: 10px 0 10px 14px;
    margin-bottom: 10px;
    p {
        width: 100%;
        margin: 0;
        color: rgba(77, 81, 90, 100);
        font-size: 14px;
        line-height: 24px;
    }
}
.need-manage-container {
    background-color: #fff;
    overflow: hidden;
    margin-bottom: 10px;
    border-radius: 6px;
    ::v-deep {
        .ant-tabs-bar {
            margin-bottom: 10px;
            background: #fff;
        }
    }
    .search-box {
        width: 100%;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        background: #fff;
        border-radius: 4px;
        padding: 20px 20px;
        .title-input {
            ::v-deep {
                .ant-input {
                    width: 210px;
                }
            }
        }
        .form-type {
            ::v-deep {
                .ant-select {
                    width: 200px;
                }
            }
        }
        .time-arr {
            width: 240px;
            ::v-deep {
                .ant-calendar-picker-input {
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;
                }
            }
        }
        .city-input {
            width: 280px;
            ::v-deep {
                .ant-form-item-control-wrapper {
                    width: 100%;
                }
            }
        }
        .add {
            color: #fff;
            background: @primary-color;
            border-radius: 2px;
            border-color: @primary-color;
            width: 90px;
        }
    }
    .table {
        height: calc(100vh - 60px - 10px - 120px - 10px - 60px);
        background: #fff;
        overflow: hidden;
        padding: 0 20px;
        .textEllipsis {
            width: 100%;
            text-align: left;
            color: @primary-color;
            cursor: pointer;
            text-decoration: underline;
        }
    }
}
.add-need-dialog-body {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    & > div {
        width: 100%;
        margin-bottom: 10px;
        &.one {
            margin-right: 40px;
        }
        .title {
            font-size: 16px;
            font-weight: bold;
            margin: 10px 0;
        }
        .content {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            .item {
                margin: 0 10px;
                cursor: pointer;
                width: 120px;
                height: 40px;
                background: #fff;
                box-shadow: 2px 3px 2px 1px rgba(0, 0, 0, 0.1);
                &:first-child {
                    margin-left: 0;
                }
                &:last-child {
                    margin-right: 0;
                }
                p {
                    font-size: 14px;
                    text-align: center;
                    line-height: 40px;
                }
            }
        }
    }
}
::v-deep {
    .ant-pagination-jump-next-custom-icon {
        display: none;
    }
    .pagination-tool {
        padding-left: 20px;
        p:first-child {
            font-size: 20px;
            margin-right: 40px;
            position: relative;
            &:after {
                content: '';
                display: block;
                width: 1px;
                height: 40px;
                background-color: #f3f3f3;
                position: absolute;
                right: -20px;
                top: 50%;
                transform: translateY(-50%);
            }
        }
        .num {
            font-size: 32px !important;
        }
        button {
            width: 100px;
            height: 36px;
            background: #ffffff;
            border: 1px solid #666666;
            border-radius: 2px;
        }
    }
}
</style>
<style lang="less">
.form-detail-text {
    margin: 0;
    font-size: 14px;
    color: #6b6c70;
    line-height: 39px;
}
</style>
